package happyloan.core;

import java.util.concurrent.TimeUnit;

import dagger.Module;
import dagger.Provides;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 全局配置Module
 */
@Module
public class GlobeConfigModule {
    private String host;
    private int connectTimeout;
    private int readTimeout;
    private int writeTimeout;
    private Interceptor interceptor;
    private GlobeConfigModule(Builder builder) {
        this.host = builder.host;
        this.connectTimeout = builder.connectTimeout;
        this.readTimeout = builder.readTimeout;
        this.writeTimeout = builder.writeTimeout;
        this.interceptor = builder.interceptor;
    }
    public static Builder builder(){
        return new Builder();
    }
    /**
     * OkHttp客户端提供者
     * @return OkHttp客户端
     */
    @Provides OkHttpClient provideOkHttpClient(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
        builder.readTimeout(readTimeout,TimeUnit.SECONDS);
        builder.writeTimeout(writeTimeout,TimeUnit.SECONDS);
        builder.addInterceptor(interceptor);
        return builder.build();
    }

    /**
     * Retrofit提供者
     * @param okHttpClient OkHttp客户端
     * @return Retrofit
     */
    @Provides Retrofit provideRetrofit(OkHttpClient okHttpClient){
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl(host);
        builder.client(okHttpClient);
        builder.addConverterFactory(GsonConverterFactory.create());
        return builder.build();
    }
    public static final class Builder{
        private String host;//请求主机地址
        private int connectTimeout = 10;//请求连接超时时间（单位：秒）
        private int readTimeout = 10;//请求读取数据超时时间（单位：秒）
        private int writeTimeout = 10;//请求写入数据超时时间（单位：秒）
        private Interceptor interceptor;
        private Builder() {
        }
        public Builder setHost(String host) {
            this.host = host;
            return this;
        }

        public Builder setConnectTimeout(int connectTimeout) {
            this.connectTimeout = connectTimeout;
            return this;
        }

        public Builder setReadTimeout(int readTimeout) {
            this.readTimeout = readTimeout;
            return this;
        }

        public Builder setWriteTimeout(int writeTimeout) {
            this.writeTimeout = writeTimeout;
            return this;
        }

        public Builder setInterceptor(Interceptor interceptor) {
            this.interceptor = interceptor;
            return this;
        }

        public GlobeConfigModule build(){
            return new GlobeConfigModule(this);
        }
    }
}
